<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Ad_Controllers_Banner extends Gio_Core_Controller
{
	/* ########################### Frontend Action ###########################*/
	
	public function loadAction()
	{
		$this->disableLayout();
		/**
		 * Get All Banner By Page Name
		 */
		$pageName = null;
		$banners = Modules_Ad_Services_Banner::loadBanners();
		$this->view->banners = $banners;
		
		$zones = Modules_Ad_Services_Zone::getAllZones(true);
		$this->view->zones = $zones;
		
		header('Content-type: application/x-javascript');
	}
	
	/* ########################### Backend Action ############################*/
	
	public function activateAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			return;
		}
		$response = 'RESULT_NOT_OK';
		$bannerId = $request->getPost('banner_id');
		$banner = Modules_Ad_Services_Banner::getById($bannerId);
		
		if (null == $banner){
			$this->getResponse()->setBody($response);
			return;	
		}
		
		$act = $request->getPost('act');
		switch ($act) {
			case 'activate':
				$status = 'active';
				break;
			case 'deactivate':
				$status = 'inactive';
				break;
		}
		$banner['status'] = $status;
		$response = 'RESULT_OK';
		Modules_Ad_Services_Banner::update($banner);
		$this->getResponse()->setBody($response);
	}
	
	public function addAction()
	{
		$request = $this->getRequest();
		
		$zones = Modules_Ad_Services_Zone::getAllZones(true);
		$this->view->zones = $zones;
		
		$pages = Modules_Core_Services_Page::dbPages();
		$this->view->pages = $pages;
		
		if ($request->isPost()) {
			$bannerData = $request->getPost('banner');
			$bannerData = Modules_Ad_Services_Banner::validate($bannerData);
			$items = $request->getPost('items');
			$bannerData['items'] = $items;
			
			if (isset($bannerData['messages_error']) && $bannerData['messages_error']) {
				$this->view->errorMessages = $bannerData['messages'];
				$this->view->bannerData = $bannerData;
				return;
			}
			
			$banner = array(
					'name' 	   	   => $this->view->STRING->escape($bannerData['name']),
					'description'  => null,
					'mode'  	   => $this->view->STRING->escape($bannerData['mode']),
					'format' 	   => $this->view->STRING->escape($bannerData['format']),
					'width' 	   => (int)$bannerData['width'],
					'height' 	   => (int)$bannerData['height'],	
					'html_code'    => $this->view->STRING->escape($bannerData['html_code']),
					'url' 		   => $this->view->STRING->escape($bannerData['url']),
					'status'	   => $this->view->STRING->escape($bannerData['status']),
					'file_url'	   => $this->view->STRING->escape($bannerData['file_url']),
					'created_date' => date('Y-m-d H:i:s'),
			);
			$bannerId = Modules_Ad_Services_Banner::add($banner, $items);
			
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('banner_add_action_success'));
			$this->redirect($this->view->url('ad_banner_add'));
			
		}
	}
	
	public function deleteAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			return;
		}
		$bannerId = $request->getPost('banner_id');
		$banner = Modules_Ad_Services_Banner::getById($bannerId);
		
		if (null == $banner){
			$this->getResponse()->setBody('RESULT_NOT_OK');
			return;	
		}
		
		/**
		 * Delete banner page assoc
		 */
		Modules_Ad_Services_BannerPageAssoc::deleteByBannerId($bannerId);
		
		Modules_Ad_Services_Banner::delete($bannerId);
		
		$this->getResponse()->setBody('RESULT_OK');
	}
	
	public function editAction()
	{
		$request = $this->getRequest();
		
		$bannerId = $request->getParam('banner_id');
		$banner   = Modules_Ad_Services_Banner::getById($bannerId);
		if (null == $banner) {
			throw new Exception('Banner with id : ' . $bannerId . ' was not found');
		}
		
		$zones = Modules_Ad_Services_Zone::getAllZones(true);
		$this->view->zones = $zones;
		
		$pages = Modules_Core_Services_Page::dbPages();
		$this->view->pages = $pages;
		
		$bannerPagesAssoc = Modules_Ad_Services_BannerPageAssoc::getBannerPageAssoc($bannerId);
		$items = array(
			'title'     => array(),
			'route'     => array(),
			'zone_id'   => array(),
			'zone_code' => array(),
			'url'       => array(),
		);
		if ($bannerPagesAssoc) {
			foreach ($bannerPagesAssoc as $index => $page) {
				$items['title'][] 	= $page['page_title'];
				$items['route'][] 	= $page['route'];
				$items['zone_id'][] = $page['zone_id'];
				$items['zone_code'][] = $page['code'];
				$items['url'][] 	= $page['page_url'];
			}
		}
		$bannerData = $banner;
		$bannerData['items'] = $items;
		$this->view->bannerData = $bannerData;
		
		if ($request->isPost()) {
			$bannerData = $request->getPost('banner');
			$bannerData = Modules_Ad_Services_Banner::validate($bannerData);
			$items = $request->getPost('items');
			$bannerData['items'] = $items;
			$bannerData['banner_id'] = $bannerId;
			
			if (isset($bannerData['messages_error']) && $bannerData['messages_error']) {
				$this->view->errorMessages = $bannerData['messages'];
				$this->view->bannerData = $bannerData;
				return;
			}
			
			$banner = array(
					'banner_id'    => $bannerData['banner_id'],
					'name' 	   	   => $this->view->STRING->escape($bannerData['name']),
					'description'  => null,
					'mode'  	   => $this->view->STRING->escape($bannerData['mode']),
					'format' 	   => $this->view->STRING->escape($bannerData['format']),
					'width' 	   => (int)$bannerData['width'],
					'height' 	   => (int)$bannerData['height'],	
					'html_code'    => $this->view->STRING->escape($bannerData['html_code']),
					'url' 		   => $this->view->STRING->escape($bannerData['url']),
					'file_url'	   => $this->view->STRING->escape($bannerData['file_url']),
					'status'	   => $this->view->STRING->escape($bannerData['status']),
			);
			$bannerId = Modules_Ad_Services_Banner::update($banner, $items);
			
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('banner_edit_action_success'));
			$this->redirect($this->view->url('ad_banner_edit', $banner));
			
		}
	}
	
	public function listAction()
	{
		$request = $this->getRequest();
		$lang    = $request->getParam('lang');
		$this->view->lang = $lang;
		$paramLang = ($lang) ? '/' . $lang : null;
		
		$perPage = 20;
		$pageIndex = (int)$request->getParam('page_index');
		if (null == $pageIndex || '' == $pageIndex || $pageIndex < 0) {
			$pageIndex = 1;
		}
		$start = ($pageIndex - 1) * $perPage;
		$this->view->pageIndex = $pageIndex;
		
		$zones = Modules_Ad_Services_Zone::getAllZones(true);
		$this->view->zones = $zones;
		
		$pages = Modules_Core_Services_Page::dbPages();
		$this->view->pages = $pages;
		
		$condition = array();
		$json = new Services_JSON();
		if ($request->isPost()) {
			$condition = $request->getPost('condition');
			$params = rawurlencode(base64_encode($json->encodeUnsafe($condition)));
		} else {
			$params = $request->getParam('q');
			($params != null)
				? ($condition = (array)$json->decode(rawurldecode(base64_decode($params))))
				: ($params = rawurlencode(base64_encode($json->encodeUnsafe($condition))));
		}
		$params = (empty($condition)) ? null : $params;
		$this->view->condition = $condition;
		
		$banners = Modules_Ad_Services_Banner::find($start, $perPage, $condition);
		$numBanners = Modules_Ad_Services_Banner::count($condition);
		
		$this->view->banners = $banners; 
		
		// Pager
		require_once LIB_DIR . DS . 'PEAR' . DS . 'Pager' . DS . 'Sliding.php';
		$pagerPath = $this->view->url('ad_banner_list');
		$pagerOptions = array(
			'mode'       	=> 'Sliding',
			'append'   		=> false,
    		'perPage'    	=> $perPage,
    		'delta'      	=> 3,
			'urlVar'		=> 'page',
			'path'			=> $pagerPath,
			'fileName'		=> (null == $params) ? 'page-%d' . $paramLang : '/page-%d' . $paramLang . '/?q=' . $params,
			'separator'		=> '',
			'nextImg' 		=> '<small class="icon arrow_right"></small>',
			'prevImg'		=> '<small class="icon arrow_left"></small>',
			'altNext'		=> '',
			'altPrev'		=> '',
			'altPage'		=> '',
    		'totalItems' 	=> $numBanners,
			'currentPage'	=> $pageIndex,
			'urlSeparator'	=> '/',
			'spacesBeforeSeparator' => 0,
			'spacesAfterSeparator' => 0,
			'curPageSpanPre' => '<a href="javascript: void();" class="current">',
			'curPageSpanPost' => '</a>'
		
		);
		$pager = new Pager_Sliding($pagerOptions);
		$this->view->pager = $pager;
	}
}